package com.bicycle.access.process;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bicycle.access.service.BicycleDataBusinessService;
import com.bicycle.common.helper.CoordinateHelper;
import com.bicycle.common.helper.RedisStringHelper;
import com.bicycle.service.cache.DataCacheOprator;
import com.bicycle.service.cache.ReginDataCache;
import com.bicycle.service.cache.RegionRelation;
import com.bicycle.service.config.MyBatisPlusConfig;
import com.bicycle.service.dto.BicycleSite;
import com.bicycle.service.dto.OrderInfo;
import com.bicycle.service.entity.BicycleBasicsBicycle;
import com.bicycle.service.entity.BicycleCommonRegion;
import com.bicycle.service.entity.BicycleDataBicycleSite;
import com.bicycle.service.entity.BicycleDataOrderInfo;
import com.bicycle.service.service.IBicycleDataBicycleSiteService;
import com.bicycle.service.service.IBicycleDataOrderInfoService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * mysql数据储存service
 */
@Slf4j
@Component
public class DataToMySqlService {

    @Autowired
    private IBicycleDataBicycleSiteService bicycleSiteService;
    @Autowired
    private IBicycleDataOrderInfoService orderInfoService;
    @Autowired
    private BicycleDataBusinessService businessService;
    @Autowired
    private RedisStringHelper redisStringHelper;


    /**
     * 车辆位置信息
     *
     * @param jsonStr
     * @see
     */
    public void bicycleSite(String jsonStr) {
        DataCacheOprator.getInstance().setRedisStringHelper(redisStringHelper);
        BicycleDataBicycleSite acsBicycleSite = new BicycleDataBicycleSite();
        BicycleSite bicycleSite = JSON.parseObject(jsonStr, BicycleSite.class);
        BeanUtil.copyProperties(bicycleSite, acsBicycleSite);
        MyBatisPlusConfig.dynamicTableName.set(DateUtil.format(new Date(), "yyyyMMdd"));


        //高德转百度 -下单
        if(StringUtils.isNotBlank(acsBicycleSite.getLat()) && StringUtils.isNotBlank(acsBicycleSite.getLng())){
            double[] site = CoordinateHelper.gcj2bd(Double.parseDouble(acsBicycleSite.getLat()), Double.parseDouble(acsBicycleSite.getLng()));
            acsBicycleSite.setLat(site[0]+"");
            acsBicycleSite.setLng(site[1]+"");
        }

        /*****************************************计算车辆行政区及街道**********************************************************/
        bicycleSite.setLat(acsBicycleSite.getLat());
        bicycleSite.setLng(acsBicycleSite.getLng());
        RegionRelation globalRelation = getRegionRelation(bicycleSite);
        if (globalRelation != null) {
            acsBicycleSite.setDistrict(globalRelation.getParentRegion().getId());
            BicycleCommonRegion globalStreet = getRegionStreet(bicycleSite, globalRelation.getRegion());
            if (globalStreet != null) {
                acsBicycleSite.setStreet(globalStreet.getId());
            }
        }

        //插入新数据
        bicycleSiteService.save(acsBicycleSite);

        // 车辆位置业务处理
        businessService.processBicycleSite(jsonStr);
    }

    /**
     * 订单基本信息
     *
     * @param jsonStr
     * @see
     */
    public void orderInfo(String jsonStr) {
        DataCacheOprator.getInstance().setRedisStringHelper(redisStringHelper);
        BicycleDataOrderInfo acsOrderInfo = new BicycleDataOrderInfo();
        OrderInfo orderInfo = JSON.parseObject(jsonStr, OrderInfo.class);
        BeanUtil.copyProperties(orderInfo, acsOrderInfo);
        MyBatisPlusConfig.dynamicTableName.set(DateUtil.format(new Date(), "yyyyMM"));

        //高德转百度 -下单
        if(StringUtils.isNotBlank(acsOrderInfo.getStartLat()) && StringUtils.isNotBlank(acsOrderInfo.getStartLng())){
            double[] orderStart = CoordinateHelper.gcj2bd(Double.parseDouble(acsOrderInfo.getStartLat()), Double.parseDouble(acsOrderInfo.getStartLng()));
            acsOrderInfo.setStartLat(orderStart[0]+"");
            acsOrderInfo.setStartLng(orderStart[1]+"");
        }
        //高德转百度 -结束
        if(StringUtils.isNotBlank(acsOrderInfo.getEndLat()) && StringUtils.isNotBlank(acsOrderInfo.getEndLng())){
            double[] orderEnd = CoordinateHelper.gcj2bd(Double.parseDouble(acsOrderInfo.getEndLat()), Double.parseDouble(acsOrderInfo.getEndLng()));
            acsOrderInfo.setEndLat(orderEnd[0]+"");
            acsOrderInfo.setEndLng(orderEnd[1]+"");
        }

        /*****************************************计算订单开始行政区及街道**********************************************************/
        BicycleSite bicycleSite = new BicycleSite();
        bicycleSite.setLat(acsOrderInfo.getStartLat());
        bicycleSite.setLng(acsOrderInfo.getStartLng());
        RegionRelation globalRelation = getRegionRelation(bicycleSite);
        if (globalRelation != null) {
            acsOrderInfo.setStartDistrict(globalRelation.getParentRegion().getId());
            BicycleCommonRegion globalStreet = getRegionStreet(bicycleSite, globalRelation.getRegion());
            if (globalStreet != null) {
                acsOrderInfo.setStartStreet(globalStreet.getId());
            }
        }

        /*****************************************计算订单结束行政区及街道**********************************************************/
        bicycleSite = new BicycleSite();
        bicycleSite.setLat(acsOrderInfo.getEndLat());
        bicycleSite.setLng(acsOrderInfo.getEndLng());
        globalRelation = getRegionRelation(bicycleSite);
        if (globalRelation != null) {
            acsOrderInfo.setEndDistrict(globalRelation.getParentRegion().getId());
            BicycleCommonRegion globalStreet = getRegionStreet(bicycleSite, globalRelation.getRegion());
            if (globalStreet != null) {
                acsOrderInfo.setEndStreet(globalStreet.getId());
            }
        }

        orderInfoService.save(acsOrderInfo);
        // 订单信息业务处理
        businessService.processOrderInfo(jsonStr);
    }


    /**
     * 根据经纬度，获取当前车辆所在行政区
     *
     * @param bicycleSite
     * @return
     * @see
     */
    @SuppressWarnings("unchecked")
    private RegionRelation getRegionRelation(BicycleSite bicycleSite) {
        RegionRelation globalRelation = null;
        Point2D.Double point = new Point2D.Double(Double.parseDouble(bicycleSite.getLat()), Double.parseDouble(bicycleSite.getLng()));
        List<RegionRelation> regionRelationList = ReginDataCache.getRegionRelationList();
        if(regionRelationList != null) {
            for (RegionRelation relation : regionRelationList) {
                if (StringUtils.isNotEmpty(relation.getParentRegion().getRegionPoints())) {
                    String pointStr = relation.getParentRegion().getRegionPoints();
                    List<JSONObject> objectList = JSON.parseObject(pointStr, ArrayList.class);
                    List<Point2D.Double> pts = new ArrayList<Point2D.Double>();
                    for (JSONObject object : objectList) {
                        Point2D.Double p = new Point2D.Double(object.getDoubleValue("lat"), object.getDoubleValue("lng"));
                        pts.add(p);
                    }
                    boolean hasArea = CoordinateHelper.IsPtInPoly(point, pts);
                    if (hasArea) {
                        globalRelation = relation;
                        log.info("getRegionRelation() 当前车辆停放的行政区ID:{},行政区名称:{}", relation.getParentRegion().getId(), relation.getParentRegion().getRegionName());
                        break;
                    }
                }
            }
        }
        return globalRelation;
    }

    /**
     * 获取所在街道
     *
     * @param bicycleSite
     * @return
     * @see
     */
    @SuppressWarnings("unchecked")
    private BicycleCommonRegion getRegionStreet(BicycleSite bicycleSite, List<BicycleCommonRegion> regionList) {
        BicycleCommonRegion globalRegion = null;
        Point2D.Double point = new Point2D.Double(Double.parseDouble(bicycleSite.getLat()), Double.parseDouble(bicycleSite.getLng()));
        if(regionList != null) {
            for (BicycleCommonRegion region : regionList) {
                if (StringUtils.isNotEmpty(region.getRegionPoints())) {
                    String pointStr = region.getRegionPoints();
                    List<JSONObject> objectList = JSON.parseObject(pointStr, ArrayList.class);
                    List<Point2D.Double> pts = new ArrayList<Point2D.Double>();
                    for (JSONObject object : objectList) {
                        Point2D.Double p = new Point2D.Double(object.getDoubleValue("lat"), object.getDoubleValue("lng"));
                        pts.add(p);
                    }
                    boolean hasArea = CoordinateHelper.IsPtInPoly(point, pts);
                    if (hasArea) {
                        globalRegion = region;
                        log.info("getRegionStreet() 当前车辆停放的街道ID:{},街道名称:{}", region.getId(), region.getRegionName());
                        break;
                    }
                }
            }
        }
        return globalRegion;
    }

}
